<template>
  <el-dialog :before-close="handleClosed" title="Deployment部署比较" v-model="visibleRef" :width="table_width">
    <el-select v-model="old_version_pod_select_value" class="m-2" placeholder="源环境"
      @change="old_version_pod_select_value_click">
      <el-option v-for="item in cluster_select_data" :key="item.kubernetes_cluster_id"
        :label="item.kubernetes_cluster_name" :value="item.kubernetes_cluster_id" />
    </el-select>
    <el-select v-model="old_version_cluster_select_value" filterable class="m-2" placeholder="源空间">
      <el-option v-for="item in old_cluster_select_data" :key="item.name" :label="item.name" :value="item.name" />
    </el-select>
    <ArrowRight style="width: 1em; height: 1em; margin-right: 8px; margin-left: 8px" />
    <el-select v-model="now_version_pod_select_value" class="m-2" placeholder="目标环境"
      @change="now_version_pod_select_value_click">
      <el-option v-for="item in cluster_select_data" :key="item.kubernetes_cluster_id"
        :label="item.kubernetes_cluster_name" :value="item.kubernetes_cluster_id" />
    </el-select>
    <el-space>
      <el-select v-model="now_version_cluster_select_value" class="m-2" filterable placeholder="目标空间">
        <el-option v-for="item in now_cluster_select_data" :key="item.name" :label="item.name" :value="item.name">
        </el-option>
      </el-select>

      <el-button type="success" @click="start_compare_deployment">比较</el-button>
      <el-tooltip class="box-item" effect="dark" content="只创建" placement="top">
        <el-switch
          v-model="if_create"
          class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #E6A23C;"
        />
      </el-tooltip>
      <el-button type="warning" @click="sync_deployment_yaml">同步</el-button>
      <el-tooltip class="box-item" effect="dark" content="刷新" placement="top">
        <el-button type="primary" @click="flush_info" icon="Refresh" />
      </el-tooltip>
    </el-space>

    <div style="width: 100%; height: 500px">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2 :columns="columns" :data="table_data" :height="height" :width="width" :estimated-row-height="50"
            style="font-size: 10px" :expand-column-key="columns[0].key">
            <template #row="props">
              <Row v-bind="props" />
            </template>
          </el-table-v2>
        </template>
      </el-auto-resizer>
    </div>

  </el-dialog>
</template>

<script lang="tsx" setup>
import { ref, watch, watchEffect, unref, onMounted, FunctionalComponent } from "vue";
import * as Request from "@/general/request";
import {
  ElCheckbox,
  ElMessage,
  CheckboxValueType
} from "element-plus";

const visibleRef = ref(false);
const cluster_select_data: any = ref([]);
const old_cluster_select_data: any = ref([]);
const now_cluster_select_data: any = ref([]);
const now_version_cluster_select_value = ref("");
const old_version_cluster_select_value = ref("");
const now_version_pod_select_value = ref("");
const old_version_pod_select_value = ref("");
const table_data = ref([]);
const if_create = ref(true)

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["closed", "update:visible"]);

watch(
  () => unref(visibleRef),
  (v) => {
    emit("update:visible", v);
  },
  {
    immediate: false,
  }
);

watchEffect(() => {
  visibleRef.value = !!props.visible;
});

function handleClosed() {
  visibleRef.value = false;
  emit("closed", false);
}

const table_width = 1200;

// 表格定义
const columns = [
{
    key: "old_version_pod_name",
    dataKey: "old_version_pod_name",
    title: "源环境deployment名称",
    width: table_width / 5,
    fixed: true
  },
  {
    key: "old_version_pod_image",
    dataKey: "old_version_pod_image",
    title: "源环境deployment镜像",
    width: table_width / 4,
    fixed: true,
  },
  {
    key: "now_version_pod_name",
    dataKey: "now_version_pod_name", //需要渲染当前列的数据字段，
    title: "目标环境deployment名称", //显示在单元格表头的文本
    width: table_width / 5, //当前列的宽度，必须设置
    fixed: true, //是否固定列
  },
  {
    key: "now_version_pod_image",
    dataKey: "now_version_pod_image",
    title: "目标环境deployment镜像",
    width: table_width / 4,
    fixed: true,
  },
  // {
  //   key: "tar_version_pod_image",
  //   dataKey: "tar_version_pod_image",
  //   title: "预打包镜像",
  //   width: table_width / 3,
  // },
];

table_data.value = [];

const now_version_pod_select_value_click = () => {
  get_env_k8s_interspace(now_version_pod_select_value, "now");
};

const old_version_pod_select_value_click = () => {
  get_env_k8s_interspace(old_version_pod_select_value, "old");
};

// 刷新
const flush_info = () => {
  if (now_version_cluster_select_value.value && old_version_cluster_select_value.value) {
    start_compare_deployment()
  }
}

// 获取勾选的条目
const get_select_items = () => {
  const table_data_: Array<object> = []
  table_data.value.map((row: any) => {
    if (Reflect.has(row, "checked") && row.checked) {
      table_data_.push(row)
    }
  })
  return table_data_
}

// 查询集群
const get_cluster = async () => {
  const response = await Request.GET(
    "/background/home/kubernetes/env_k8s_cluster"
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      cluster_select_data.value = return_data.data;
      ElMessage.success(return_data.msg);
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 查询空间下拉选择
const get_env_k8s_interspace = async (kubernetes_cluster_id :any, old_or_now: string) => {
  const response = await Request.GET("/background/home/kubernetes/namespace", {
    kubernetes_cluster_id: kubernetes_cluster_id.value,
  });
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      if (old_or_now === "old") {
        old_cluster_select_data.value = return_data.data;
      } else {
        now_cluster_select_data.value = return_data.data;
      }
      // ElMessage.success(return_data.msg)
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 版本比较
const start_compare_deployment = async () => {
  const response = await Request.GET(
    "/background/home/kubernetes/start_compare_deployment_yaml",
    {
      now_kubernetes_cluster_id: now_version_pod_select_value.value,
      old_kubernetes_cluster_id: old_version_pod_select_value.value,
      now_version_cluster_select_name: now_version_cluster_select_value.value,
      old_version_cluster_select_name: old_version_cluster_select_value.value,
    }
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      table_data.value = return_data.data;
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 同步勾选yaml
const sync_deployment_yaml = async () => {

  const check_data = get_select_items()

  const response = await Request.PUT(
    "/background/home/kubernetes/sync_deployment_yaml", {
    "old_kubernetes_cluster_id": old_version_pod_select_value.value,
    "now_kubernetes_cluster_id": now_version_pod_select_value.value,
    "now_kubernetes_cluster_namespace": now_version_cluster_select_value.value,
    "old_kubernetes_cluster_namespace": old_version_cluster_select_value.value,
    "data": check_data,
    "if_create": if_create.value
  }
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      ElMessage.success(return_data.msg);
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

onMounted(get_cluster);

// 表格行下拉选择
const Row = ({ cells, rowData }:any) => {
  if (rowData.is_children) {
    return (
      <el-row>
        <el-col span={12}>
          <el-timeline style="padding-top: 20px; width: 150px">
            <el-timeline-item color={"#67C23A"}>
              {rowData.old_pod_image_version}
            </el-timeline-item>
            <el-timeline-item color={"#E6A23C"}>
              {rowData.now_pod_image_version}
            </el-timeline-item>
          </el-timeline>
        </el-col>
        <el-col span={12}>
          <el-timeline style="padding-top: 20px; width: 300px">
            <el-timeline-item color={"#67C23A"}>
              {rowData.old_image_repository}
            </el-timeline-item>
            <el-timeline-item color={"#E6A23C"}>
              {rowData.now_image_repository}
            </el-timeline-item>
          </el-timeline>
        </el-col>
      </el-row>
    );
  }
  return cells;
};

Row.inheritAttrs = false;

type SelectionCellProps = {
  value: boolean
  intermediate?: boolean
  onChange: (value: CheckboxValueType) => void
}

const SelectionCell: FunctionalComponent<SelectionCellProps> = ({
  value,
  intermediate = false,
  onChange,
}) => {
  return (
    <ElCheckbox
      onChange={onChange}
      modelValue={value}
      indeterminate={intermediate}
    />
  )
}

columns.unshift({
  key: 'selection',
  width: 50,
  cellRenderer: ({ rowData }: any) => {
    const onChange = (value: CheckboxValueType) => (
      rowData.checked = value
    )
    return <SelectionCell value={rowData.checked} onChange={onChange} />
  },

  headerCellRenderer: () => {
    const _data = unref(table_data)
    const onChange = (value: CheckboxValueType) =>
    (table_data.value = _data.map((row) => {
      row.checked = value
      return row
    }))
    const allSelected = _data.every((row) => row.checked)
    const containsChecked = _data.some((row) => row.checked)

    return (
      <SelectionCell
        value={allSelected}
        intermediate={containsChecked && !allSelected}
        onChange={onChange}
      />
    )
  },
})
</script>

<style>
.el-table-v2__row-depth-0 {
  height: 20px;
}

.el-table-v2__cell-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
